package com.tgy.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/***
 * @ClassName: NewClassTest
 * @Description: 动态创建对象，通过反射
 * @Auther: 送一一块二向箔
 * @Date: 19:37 2021/12/1
 * @version : V1.0
 */
public class NewClassTest {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得Class对象
        Class<User> userClass = User.class;
        //构造一个对象，默认调用无参对象
        User user = userClass.newInstance();
        System.out.println(user);

        /**
         * 通过构造器创建对象,适用于没有默认的无参构造方法
         */
        Constructor<User> declaredConstructor = userClass.getDeclaredConstructor(String.class, int.class, int.class);
        User user1 = declaredConstructor.newInstance("姓名", 1, 2);
        System.out.println(user1.getName());
        System.out.println(user1.toString());

        /**
         * 通过反射调用普通方法
         */
        User user2 = userClass.newInstance();
        Method setName = userClass.getDeclaredMethod("setName", String.class);
        //激活(需要执行的对象，传入的参数)
        setName.invoke(user2,"user2名字");
        System.out.println(user2.getName());

        /**
         * 通过反射操作属性
         */
        User user3 = userClass.newInstance();
        Field name = userClass.getDeclaredField("name");

        //不能直接操作私有属性，需要关闭安全检测 打开通过
        name.setAccessible(true);
        name.set(user3,"通过反射操作属性");
        System.out.println(user3.getName());

    }
}

